package com.gitee.netty.netty_demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.AttributeKey;

/**
 * 开发人员   YooLin1c
 * 编写日期   2018/7/21
 * 联系邮箱   401664157@qq.com
 * 作用描述
 */
public class Server {
    public static void main(String[] args) throws Exception {
        // 对应socket_demo的Server类中的线程
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // 对应socket_demo的Client类中的线程
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            // 关联两个线程
            bootstrap.group(bossGroup, workerGroup)
                    // 设置服务端的SocketChannel
                    .channel(NioServerSocketChannel.class)
                    // 设置客户端的每个连接的TCP属性
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    // 每次创建客户端连接时绑定基本的属性
                    .childAttr(AttributeKey.newInstance("childAttr"), "childAttrValue")
                    // 服务器启动过程时的逻辑
                    .handler(new ServerHandler())
                    // 为每个客户端连接配置逻辑处理链
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            // socketChannel.pipeline().addLast()
                        }
                    });
            // 创建服务端Channel，绑定8888端口
            ChannelFuture channelFuture = bootstrap.bind(8888).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
